import React, { Component } from "react";
import { View, Alert, Platform } from "react-native";
import {
  ListItem,
  Button,
  Avatar,
  Input,
  CheckBox
} from "react-native-elements";
import SyanImagePicker from "react-native-syan-image-picker";
import DateTimePicker from "react-native-modal-datetime-picker";
import moment from "moment";
import CustomHeader from "../../components/CustomHeader";
import AliyunOSS from "aliyun-oss-react-native";
import {
  getRandomFileName,
  getFileExtension,
  request,
  getNameByUrl
} from "../../utils";
import config from "../../utils/config";
import { MyButton } from "../../components/MyButton";

export class AddPerson extends Component {
  constructor(props) {
    super(props);
    this.state = {
      itemId: props.navigation.getParam("itemId", 0),
      showSelectDate: false,
      头像: "",
      生日: "",
      姓名: "",
      性别: "",
      newAvatarName: ""
    };
    AliyunOSS.enableDevMode();
    AliyunOSS.initWithServerSTS(
      config.aliyunOssSts,
      "oss-cn-beijing.aliyuncs.com",
      {
        maxRetryCount: 3,
        timeoutIntervalForRequest: 30,
        timeoutIntervalForResource: 24 * 60 * 60
      }
    );
  }
  componentDidMount = () => {
    const { itemId } = this.state;
    if (itemId) {
      request("person/info", { id: itemId }, pInfo =>
        this.setState({
          头像: pInfo.Avatar,
          newAvatarName: getNameByUrl(pInfo.Avatar),
          生日: pInfo.Birthday,
          姓名: pInfo.Name,
          性别: pInfo.Sex
        })
      );
    }
  };

  提交 = _ => {
    const { 头像, 姓名, 性别, 生日, itemId, newAvatarName } = this.state;
    const { navigation } = this.props;

    if (!姓名) {
      return;
    }

    request(
      "person/add",
      {
        Name: 姓名,
        Avatar: newAvatarName ? newAvatarName : 头像,
        Birthday: 生日,
        Sex: 性别,
        Id: itemId
      },
      _ => navigation.goBack(),
      data => Alert.alert(data)
    );
  };

  删除 = _ => {
    const { itemId, 姓名 } = this.state;
    const { navigation } = this.props;
    Alert.alert("确定要删除 " + 姓名 + " 吗?", "", [
      { text: "取消" },
      {
        text: "确定",
        onPress: _ => {
          request(
            "person/delete",
            { id: itemId },
            _ => navigation.goBack(),
            data => Alert.alert(data)
          );
        }
      }
    ]);
  };

  uploadAvatar = image => {
    let filePath = Platform.OS == "ios" ? image.uri : image.original_uri;
    this.setState({ 头像: filePath });
    let newName = getRandomFileName() + "." + getFileExtension(filePath);
    AliyunOSS.asyncUpload("maternal-baby", newName, filePath)
      .then(res => {
        console.log(res);
        this.setState({ newAvatarName: newName });
      })
      .catch(error => console.log(error));
  };
  selectImage = _ => {
    SyanImagePicker.showImagePicker(
      {
        imageCount: 1,
        isRecordSelected: false,
        showCropCircle: true,
        isCrop: true
      },
      (err, photos) => {
        if (!err) {
          this.uploadAvatar(photos[0]);
        }
      }
    );
  };
  componentWillUnmount = _ => {
    SyanImagePicker.removeAllPhoto();
    SyanImagePicker.deleteCache();
  };

  personInfo = (itemId, 姓名) => {
    const { navigation } = this.props;
    return (
      <View>
        <ListItem
          title="查看二维码"
          bottomDivider
          rightIcon={{ name: "right", type: "antdesign" }}
          onPress={_ =>
            navigation.navigate("PersonQrCode", { pId: itemId, pName: 姓名 })
          }
        />
        <ListItem
          title="查看监护人"
          bottomDivider
          rightIcon={{ name: "right", type: "antdesign" }}
          onPress={_ =>
            navigation.navigate("PersonGuardian", { pId: itemId, pName: 姓名 })
          }
        />
        <ListItem
          title="查看全部记录"
          bottomDivider
          rightIcon={{ name: "right", type: "antdesign" }}
          onPress={_ =>
            navigation.navigate("AllRecord", { pId: itemId, pName: 姓名 })
          }
        />
        <MyButton
          title="删除"
          containerStyle={{ margin: 16 }}
          onPress={this.删除}
        />
      </View>
    );
  };
  render() {
    const { 头像, showSelectDate, 生日, 姓名, 性别, itemId } = this.state;
    return (
      <View>
        <CustomHeader
          title={(itemId ? "编辑" : "添加") + "被监护人"}
          right="check"
          onRightClick={this.提交}
        />
        <ListItem
          title="头像"
          bottomDivider
          rightElement={
            <Avatar
              source={{ uri: 头像 }}
              size={64}
              rounded
              onPress={this.selectImage}
            />
          }
        />
        <ListItem
          title="姓名"
          bottomDivider
          rightElement={
            <Input
              containerStyle={{ width: 200 }}
              inputStyle={{ textAlign: "right" }}
              defaultValue={""}
              value={姓名}
              onChangeText={text => this.setState({ 姓名: text })}
            />
          }
        />
        <ListItem
          title="性别"
          bottomDivider
          rightElement={
            <View
              style={{
                display: "flex",
                flexDirection: "row",
                width: 200
              }}
            >
              <CheckBox
                title="男"
                containerStyle={{
                  backgroundColor: "transparent",
                  borderColor: "transparent"
                }}
                onPress={_ => this.setState({ 性别: "男" })}
                checked={性别 == "男"}
                checkedIcon="dot-circle-o"
                uncheckedIcon="circle-o"
              />
              <CheckBox
                title="女"
                containerStyle={{
                  backgroundColor: "transparent",
                  borderColor: "transparent"
                }}
                onPress={_ => this.setState({ 性别: "女" })}
                checked={性别 == "女"}
                checkedIcon="dot-circle-o"
                uncheckedIcon="circle-o"
              />
            </View>
          }
        />
        <ListItem
          title="生日"
          bottomDivider
          rightElement={
            <MyButton
              title={生日 ? 生日 : "选择"}
              type="clear"
              onPress={_ => this.setState({ showSelectDate: true })}
            />
          }
        />

        {itemId ? this.personInfo(itemId, 姓名) : null}

        <DateTimePicker
          isVisible={showSelectDate}
          onConfirm={date => {
            this.setState({
              showSelectDate: false,
              生日: moment(date).format("YYYY-MM-DD")
            });
          }}
          onCancel={_ => this.setState({ showSelectDate: false })}
          is24Hour={true}
          mode="date"
        />
      </View>
    );
  }
}

export default AddPerson;
